﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Microsoft.Web.Mvc;
using SapaFinance.DTO;
using SapaFinance.Services;
using Telerik.Web.Mvc;

namespace SapaFinance.UI.Controllers
{
    public class OrderController : Controller
    {
        private readonly IOrderService _orderService;

        public OrderController(IOrderService orderService)
        {
            _orderService = orderService;
        }

        public virtual ActionResult Index()
        {
            var dtoList = _orderService.GetListDTO();
            //важно указать имя view, т.к. его использует Update при !ModelState.IsValid. Если оставить пустое, то ищет по имени Update
            return View("Index", dtoList);
        }

        [HttpPost]
        [GridAction]
        public virtual ActionResult Insert(OrderDTO dto)
        {
            dto.CurrentUser = User.Identity.Name;
            ValidateDto(dto);
            if (ModelState.IsValid)
            {
                if (TempData["requests"] != null)
                {
                    var requestsGuid = TempData["requests"] as Guid[];
                    dto.LinkedRequests = requestsGuid;
                    var errors = _orderService.CheckOrderSum(dto);
                    if (!errors.Any())
                    {
                        _orderService.Insert(dto);
                        return this.RedirectToAction(x => x.Index());
                    }
                    foreach (var error in errors)
                    {
                        ModelState.AddModelError(string.Empty, error);
                        TempData["requests"] = requestsGuid;  //без этой строки пропадает информация после ввода изменений при создании распоряжения.
                    }
                }
            }
            return View("CreateOrder", dto);
        }

        private void ValidateDto(OrderDTO dto)
        {
            if (dto.SelectedAgent.Equals(Guid.Empty)) ModelState.AddModelError("SelectedAgent", "Агент должен быть определен");
        }

        [HttpPost]
        [GridAction]
        public virtual ActionResult Update(OrderDTO dto)
        {
            dto.CurrentUser = User.Identity.Name;
            ValidateDto(dto);
            if (ModelState.IsValid)
            {
                _orderService.Update(dto);
                return this.RedirectToAction(x => x.Index());
            }
            return Index();
        }

        [HttpPost]
        [GridAction]
        public virtual ActionResult Delete(Guid id)
        {
            _orderService.Delete(id);
            return this.RedirectToAction(x => x.Index());
        }

        public virtual ActionResult CreateOrder()
        {
            if (TempData["requests"] != null)
            {
                var requestsGuid = TempData["requests"] as Guid[];
                var orderdto = _orderService.CreateOrder(requestsGuid);
                TempData["requests"] = requestsGuid;
                orderdto.LinkedRequests = requestsGuid;
                return View("CreateOrder", orderdto);
            }
            return this.RedirectToAction(x => x.Index());
        }

        public virtual ActionResult Command(Guid[] checkedRecords, string submitButton)
        {
            switch (submitButton)
            {
                case "ProcessOrder":

                    if (checkedRecords != null)
                    {
                        //var errors = _requestService.VerifyAggregateToOrder(checkedRecords);
                        //if (!errors.Any())
                        //{
                        //    TempData["requests"] = checkedRecords;
                        //    //чтобы передать массив в CreateOrder, нужно добавить в RouteMap, а пока храним в TempData
                        //    return this.RedirectToAction<OrderController>(x => x.CreateOrder());
                        //}
                        //foreach (var error in errors)
                        //{
                        //    ModelState.AddModelError(string.Empty, error);
                        //}

                    }
                    else
                    {
                        ModelState.AddModelError(string.Empty, "Ни одна заявка не выбрана");
                    }

                    break;
            }
            return Index();

        }
        [HttpPost]
        public ActionResult DisplayCheckedOrders(Guid[] checkedRecords)
        {
            return PartialView("GetCheckedOrders", _orderService.GetListDTO().Where(o => checkedRecords.Contains(o.UID)));
        }
    }
}